package com.qf6.conf;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Component
@PropertySource("classpath:jdbc.properties")
public class MyBatisConfig {

    @Value("${jdbc.driver}")
    private String dirver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean
    public DataSource getDs(){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(dirver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }

    @Bean
    public static MapperScannerConfigurer msc(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.qf6.mapper");
        return msc;
    }


    @Bean
    public SqlSessionFactoryBean ssfb(DataSource ds){
        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();

        Configuration conf = new Configuration();
        conf.setLogImpl(StdOutImpl.class);
        ssfb.setConfiguration(conf);

        ssfb.setDataSource(ds);
        return ssfb;
    }

    /*
        将事务的平台管理器交给spring控制
     */
    @Bean("transactionManager")
    public DataSourceTransactionManager dstm(DataSource ds){
        DataSourceTransactionManager dstm = new DataSourceTransactionManager();
        dstm.setDataSource(ds);
        return dstm;
    }
}
